/*
 * PeerCheckTasks - TimerTask that checks for good/bad up/downloaders. Copyright
 * (C) 2003 Mark J. Wielaard
 * 
 * This file is part of Snark.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package org.klomp.snark;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * TimerTask that checks for good/bad up/downloader. Works together with the
 * PeerCoordinator to select which Peers get (un)choked.
 */
class PeerCheckerTask extends TimerTask
{
    private static final long KILOPERSECOND = 1024 * (Knobs.CHECK_PERIOD / 1000);

    private final PeerCoordinator coordinator;
    
    private int runs = 0;
    
    private int totalUploadedChunks = 0;
    
    private int totalDownloadedChunks = 0;
    
    private int totalInterested = 0;

    PeerCheckerTask (PeerCoordinator coordinator)
    {
        this.coordinator = coordinator;
    }

    @Override
    public void run ()
    {
        synchronized (coordinator.peers) {
            // Calculate total uploading and worst downloader.
            long worstdownload = Long.MAX_VALUE;
            Peer worstDownloader = null;

            int peers = 0;
            int uploaders = 0;
            int downloaders = 0;
            int interested = 0;
            int interesting = 0;
            int choking = 0;
            int choked = 0;

            long uploaded = 0;
            long downloaded = 0;
            long totalDownloadChunks = 0;
            long totalUploadChunks = 0;
            long totalRequestsOut = 0;

            
            // Calculate the totals for this round first
            Iterator it1 = coordinator.peers.iterator();
            while (it1.hasNext()) {
            	
            	Peer peer = (Peer)it1.next();
            	
                long upload = peer.getUploaded();
                uploaded += upload;
                
                long uploadChunks = peer.getUploadChunks();
                totalUploadChunks += uploadChunks;
                
                long download = peer.getDownloaded();
                downloaded += download;
                
                long downloadChunks = peer.getDownloadChunks();
                totalDownloadChunks += downloadChunks;
                
                long requestsOut = 0l; 
                PeerState s = peer.state;
                if (s != null) {
                	requestsOut = peer.state.getNumberOfOutstandingRequests();
                }
                
                totalRequestsOut += requestsOut;
            
            }
            
            int peerID = 0;
            

            
            Iterator it2 = coordinator.peers.iterator();
            while (it2.hasNext()) {
            	
            	peerID++;
            	
            	Peer peer = (Peer)it2.next();

            	float propShare;
            	
            	long upload = peer.getUploaded();
            	long download = peer.getDownloaded();
            	long downloadChunks = peer.getDownloadChunks();
            	long uploadChunks = peer.getUploadChunks();
            	
            	if (downloaded != 0) {
//                	propShare = (float)download / (float)downloaded;
            		propShare = (float)downloadChunks / totalDownloadChunks;
            	} else {
            		propShare = (float)1 / coordinator.peers.size();
            	}
            	
            	peer.setPropShare(propShare, Knobs.UPLOAD_CHUNKS);
            	
                // Remove dying peers
                if (!peer.isConnected()) {
                    it2.remove();
                    continue;
                }

                peers++;

                if (!peer.isChoking()) {
                    uploaders++;
                }
                if (!peer.isChoked() && peer.isInteresting()) {
                    downloaders++;
                }
                if (peer.isInterested()) {
                    interested++;
                }
                if (peer.isInteresting()) {
                    interesting++;
                }
                if (peer.isChoking()) {
                    choking++;
                }
                if (peer.isChoked()) {
                    choked++;
                }
                

                
                peer.resetCounters();
                
                log.log(Level.FINEST, peer + ":" + " ul: " + upload
                        / KILOPERSECOND + " dl: " + download / KILOPERSECOND
                        + " i: " + peer.isInterested() + " I: "
                        + peer.isInteresting() + " c: " + peer.isChoking() + " C: "
                        + peer.isChoked());
            
            }
            
            runs++;
            
            // Calculate average uploads and downloads, only useful for logging
            totalUploadedChunks += totalUploadChunks;
            totalDownloadedChunks += totalDownloadChunks;
            int averageUploadChunks = (int)totalUploadedChunks / runs;
            int averageDownloadChunks = (int)totalDownloadedChunks / runs;
            
            // Logging commented out,left for demonstrationa purposes.
//            System.out.println("##############################################################");
//            System.out.println("Average uploaded chunks per round: " + averageUploadChunks);
//            System.out.println("Average downloaded chunks per round: " + averageDownloadChunks);
//            System.out.println("##############################################################");
            
            // Calculate average num. of interested peers.
            totalInterested += interested;
            int averageInterested = (int)totalInterested / runs;
            
            // our interest is declining, reveal our hidden pieces!
            if (interested < averageInterested) {
            	
            	System.out.println("Interest levels dropped, reveal hidden pieces!");
            	
            	coordinator.revealHiddenPieces();
            }
            
            
            // Determine if we are nearing the end.
            int chunksLeft = coordinator.getChunksLeft();
            
            // N as many requests out as chunks left. Eg, twice as many open requests
            // as chunks we need, could be safe to say we are ending.
            if (chunksLeft <= (totalRequestsOut / Knobs.REQUESTS_TO_CHUNKSLEFT)) {
            	
            	System.out.println("Starting end game!");
            	
            	coordinator.setIsEndGame(true);
            }
            
            
            // Sort our wanted pieces by rarity.
            coordinator.sortWantedPieces();
            
            // Resync actual uploaders value
            // (can shift a bit by disconnecting peers)
            coordinator.uploaders = uploaders;


        }
    }

    protected static final Logger log = Logger.getLogger("org.klomp.snark.peer");
    
}
